import Head from 'next/head';
import Link from 'next/link';
import { GetServerSideProps, InferGetServerSidePropsType } from 'next';
import type { Data } from '@/pages/api/post/getPostByCatName';
import { request } from '@/components/server/utils/request';
import { SiteLayout } from '@/components/Layout';
import { Typography, List, Pagination } from 'antd';
import { useRouter } from 'next/router';
export default function Index({
  data,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  const router = useRouter();
  return (
    <>
      <Head>
        <link
          rel="shortcut icon"
          type="image/x-icon"
          href="https://unpkg.byted-static.com/latest/byted/arco-config/assets/favicon.ico"
        />
        <title>{data?.catName}</title>
      </Head>

      <Typography.Title>{data?.catName}</Typography.Title>
      <List
        dataSource={data?.posts}
        footer={
          <Pagination
            onChange={(page, pageSize) => {
              router.push({
                pathname: '/blog/category/[id]/[page]',
                query: { page: page, id: data?.catName },
              });
            }}
            pageSize={10}
            hideOnSinglePage
            total={data?.total}
          ></Pagination>
        }
        renderItem={(item) => (
          <List.Item>
            <Link
              href={{
                pathname: '/blog/view/[id]',
                query: { id: item.id },
              }}
            >
              {item.title}
            </Link>
          </List.Item>
        )}
      ></List>
    </>
  );
}
Index.Layout = SiteLayout;
export const getServerSideProps: GetServerSideProps<{
  data?: Data;
}> = async (context) => {
  const { id, page } = context.query;
  if (typeof id === 'string') {
    return request<Data>('/api/post/getPostByCatName', {
      method: 'post',
      data: { catName: id, page, size: 10 },
    })
      .then((res) => {
        return {
          props: {
            data: res || {},
          },
        };
      })
      .catch((e) => {
        console.log(e);
        return { notFound: true };
      });
  } else {
    return {
      notFound: true,
    };
  }
};
